package com.example.the8

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val listView=findViewById<ListView>(R.id.listView)
        thread {
            // 读取并打印 JSON 数据
            val jsonData = readFileFromRaw(R.raw.citycode)
            val gson= Gson()
            val CityType=object :TypeToken<List<CityItem>>(){}.type
            var cities:List<CityItem> =gson.fromJson(jsonData,CityType)
            cities=cities.filter { it.city_code!="" }
            runOnUiThread {
                val adapter = ArrayAdapter<CityItem>(this,android.R.layout.simple_list_item_1,cities)
                listView.adapter=adapter
                listView.setOnItemClickListener { _, _, position, _ ->
                    val cityCode=cities[position].city_code
                    val intent=Intent(this,SecondActivity::class.java)
                    intent.putExtra("city_code",cityCode)
                    Log.d("SecondActivity","code:$cityCode")
                    startActivity(intent)
                }
            }

            Log.d("MainActivity", "$cities")
        }


    }
    fun readFileFromRaw(rawName: Int): String? {
        try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            var result: String? = ""
            while (bufReader.readLine().also({ line = it }) != null) {
                result += line
            }
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
}